﻿using System.Collections.Generic;
using System.Linq;
using UcAsp.Net.Model;

namespace UcAsp.Net.MSSQLDAL
{
    public class ArticlesPageDAL : UcAsp.Net.IDAL.IArticlesPageDAL
    {
        public ArticlesPage Insert(ArticlesPage model)
        {
            using (UcAspNetEntities entities = new UcAspNetEntities())
            {
                var page = entities.ArticlesPages.Where(o => o.ArticlesID == model.ArticlesID);
                Articles art = entities.Articless.FirstOrDefault(o => o.ID == model.ArticlesID);
                art.PageCount = page.Count() + 1;
                System.Data.Entity.Infrastructure.DbEntityEntry<Articles> entry = entities.Entry<Articles>(art);
                entry.State = System.Data.EntityState.Modified;
                entities.ArticlesPages.Add(model);
                entities.SaveChanges();
                return model;
            }
        }

        public ArticlesPage GetArticlesPageByPageID(int artclesid, int pageid)
        {
            using (UcAspNetEntities entities = new UcAspNetEntities())
            {
                return entities.ArticlesPages.FirstOrDefault(o => o.ArticlesID == artclesid & o.PageID == pageid);
            }
        }

        public List<ArticlesPage> GetArticlesPageByArticlesID(int artclesid)
        {
            using (UcAspNetEntities entities = new UcAspNetEntities())
            {
                return entities.ArticlesPages.Where(o => o.ArticlesID == artclesid).ToList();
            }
        }

        public ArticlesPage GetArticlesPageByID(int id)
        {
            using (UcAspNetEntities entities = new UcAspNetEntities())
            {
                return entities.ArticlesPages.FirstOrDefault(o => o.ID == id);
            }
        }

        public ArticlesPage Update(ArticlesPage model)
        {
            using (UcAspNetEntities entities = new UcAspNetEntities())
            {
                System.Data.Entity.Infrastructure.DbEntityEntry<ArticlesPage> entry = entities.Entry<ArticlesPage>(model);
                entry.State = System.Data.EntityState.Modified;
                entities.SaveChanges();
                return model;
            }
        }

        public bool Delete(int articleid)
        {
            using (UcAspNetEntities entities = new UcAspNetEntities())
            {
                entities.Database.ExecuteSqlCommand("delete from ArticlesPage where ArticlesID ='" + articleid + "'");
                return true;
            }
        }
    }
}